export function isJson(str: any) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

function saveFile(file: string, savePath: string) {
  const saveLink = document.createElement('a');
  saveLink.download = savePath;
  saveLink.href = URL.createObjectURL(file);
  saveLink.style.display = 'none';
  document.body.appendChild(saveLink);
  saveLink.click();
  document.body.removeChild(saveLink);
}

export function downloadFile(url: string, savePath: string) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (this.status === 200) {
        saveFile(this.response, savePath);
        resolve();
      } else {
        reject(new Error('Failed to download file'));
      }
    };
    xhr.onerror = function () {
      reject(new Error('Network error'));
    };
    xhr.send();
  });
}

export function toBase64(url) {
  return fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    });
}

export function formatArr(arr: any[]): any[] {
  if (!Array.isArray(arr)) return;
  const map = new Map<string, any>();
  arr.forEach((item) => {
    const curr = { ...item };
    if (map.has(curr.parentId)) {
      const parent = map.get(curr.parentId);
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(curr);
    } else {
      map.set(curr.id, curr);
    }
  });

  return Array.from(map.values());
}

export function arrayToTree(array, paramsKey) {
  if (!Array.isArray(array)) return;
  // pid 和id 都是字符串
  const pid = paramsKey.pid;
  const id = paramsKey.id;

  let copyArr = JSON.parse(JSON.stringify(array));

  // 筛选出没有父级的数据
  array?.forEach(function (item) {
    copyArr = copyArr.filter(function (child) {
      return child[pid] !== item[id];
    });
  });

  // 递归转换
  function treeLoop(arr = [], total = []) {
    for (let i = 0; i < arr.length; i++) {
      const aid = arr[i][id];

      let children = total.filter(function (child) {
        return child[pid] === aid;
      });
      if (children.length > 0) {
        children = treeLoop(children, total);
      }

      arr[i].children = children;
    }

    return arr;
  }

  return treeLoop(copyArr, array);
}

export function arrayToTree2(array, paramsKey) {
  if (!Array.isArray(array)) return;
  // pid 和id 都是字符串
  const pid = paramsKey.pid;
  const id = paramsKey.id;

  let copyArr = JSON.parse(JSON.stringify(array));

  // 筛选出没有父级的数据
  array?.forEach(function (item) {
    copyArr = copyArr.filter(function (child) {
      return child[pid] !== item[id];
    });
  });

  // 递归转换
  function treeLoop(arr = [], total = []) {
    for (let i = 0; i < arr.length; i++) {
      const aid = arr[i][id];
      let children = total.filter(function (child) {
        return child[pid] === aid;
      });
      if (children.length > 0) {
        children = treeLoop(children, total);
      }
      arr[i].children = children;
    }
    return arr;
  }

  return treeLoop(copyArr, array);
}

// url转base64
export async function imageURLToBase64(url: string) {
  let count = 0;

  return fetch(url)
    .then((response) => {
      return response.blob();
    })
    .then(
      (blob) =>
        new Promise((resolve, reject) => {
          const img = new Image();
          img.src = url;
          img.onload = function () {
            count++;
            if (count === 2) {
              resolve({
                imageBase64: reader.result,
                imageWidth: img.width,
                imageHeight: img.height,
              });
            }
          };

          const reader = new FileReader();
          reader.onloadend = () => {
            count++;
            if (count === 2) {
              resolve({
                imageBase64: reader.result,
                imageWidth: img.width,
                imageHeight: img.height,
              });
            }
          };
          reader.onerror = reject;
          reader.readAsDataURL(blob);
        }),
    );
}

// 判断是否是目录
export function isCommonFileType(ext: string) {
  const commonFileTypes = [
    '.txt',
    '.doc',
    '.docx',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.pdf',
    '.jpg',
    '.jpeg',
    '.png',
    '.gif',
    '.mp3',
    '.mp4',
    '.zip',
    '.tar.gz',
    '.sql',
    '.html',
    '.css',
    '.js',
    '.json',
    '.md',
    '.xml',
  ];

  for (let i = 0; i < commonFileTypes.length; i++) {
    if (ext.endsWith(commonFileTypes[i])) {
      return true;
    }
  }
  return false;
}

export function downloadBlob(blob, filename) {
  // 创建新的 URL 对象
  const url = window.URL.createObjectURL(blob);

  // 创建隐藏的可下载链接
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.download = filename;

  // 添加到文档中
  document.body.appendChild(link);

  // 触发点击
  link.click();

  // 清理
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}

// 26个字母
// const LETTERS = []
// export const LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
export const LETTERSMAP: Record<number, string> = {
  0: 'A',
  1: 'B',
  2: 'C',
  3: 'D',
  4: 'E',
  5: 'F',
  6: 'G',
  7: 'H',
  8: 'I',
  9: 'J',
  10: 'K',
  11: 'L',
  12: 'M',
  13: 'N',
  14: 'O',
  15: 'P',
  16: 'Q',
  17: 'R',
  18: 'S',
  19: 'T',
  20: 'U',
  21: 'V',
  22: 'W',
  23: 'X',
  24: 'Y',
  25: 'Z',
  26: 'AA',
};

export function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// 为所有的单元格添加边框 且 居中
export const allCellMiddle = (_sheet1: any) => {
  // 遍历所有单元格并添加边框
  _sheet1.eachRow(function (row) {
    row.eachCell(function (cell) {
      const borderStyle = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      };

      cell.border = borderStyle;
      cell.alignment = {
        vertical: 'middle', //垂直居中
        horizontal: 'left', //水平居中
      };
    }); // true表示递归处理子数组中的单元格
  });
};

// 特定单元格批量操作
export const cellBatchStyle = (_sheet1: any, cells: any) => {
  cells?.forEach((_cell) => {
    _sheet1.getCell(_cell).alignment = {
      horizontal: 'center',
      vertical: 'middle', //垂直居中
    };
  });
};

// 获取图片宽高-转化为excel宽高
export const getExcelImageWidth = (
  imageWidth: number,
  imageHeight: number,
  excelHeight?: any,
) => {
  return (imageWidth / imageHeight) * excelHeight ?? 145;
};

// 设置一行的数据
export const setRowData = (_sheet1: any, row: any, rowIndex: number) => {
  // _sheet1.getCell('A4').value = '售价';
  row?.forEach((_item, index) => {
    _sheet1.getCell(`${LETTERSMAP[index]}${rowIndex}`).value = _item;
  });
};

// 批量合并单元格
export const mergeCells = (_sheet1: any, cells: any[]) => {
  cells?.forEach((_cell) => {
    _sheet1.mergeCells(_cell);
  });
};

// 导出-步骤-excel导出逻辑
export const renderExcelStep = (_sheet1: any, list: any[]) => {};

// 三种配方导出公用的配置
export const exportCommon: any = {
  // 公用的col
  commonCol: (title: string) => {
    return [
      [title],
      [
        '品项类别',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
      ],
      [
        '品项编码',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
      ],
      [
        '品项编码',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
      ],
      [
        '售价',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '毛利率',
        '',
        '',
        '',
        '',
        '成本',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
      ],
    ];
  },
  commonMerge: (_sheet1) => {
    mergeCells(_sheet1, [
      'A1:AA1',
      'A2:D2',
      'E2:I2',

      'A3:D3',
      'E3:I3',

      'A4:D4',
      'E4:I4',

      'A5:D5',
      'E5:I5',
      'J5:K5',
      'L5:N5',
      'O5:P5',
      'Q5:S5',
      'T5:AA5',

      // 'A7:B7',
      // 'C7:H7','I7:K7','L7:N7','O7:P7','Q7:S7','T7:V7','W7:Y7','Z7:AA7',
    ]);
  },
};

export function arrayToTreeForTable(array, paramsKey) {
  if (!Array.isArray(array)) return;
  // pid 和id 都是字符串
  const pid = paramsKey.pid;
  const id = paramsKey.id;

  let copyArr = JSON.parse(JSON.stringify(array));

  // 筛选出没有父级的数据
  array?.forEach(function (item) {
    copyArr = copyArr.filter(function (child) {
      return child[pid] !== item[id];
    });
  });

  // 递归转换
  function treeLoop(arr = [], total = []) {
    for (let i = 0; i < arr.length; i++) {
      const aid = arr[i][id];

      let children = total.filter(function (child) {
        return child[pid] === aid;
      });
      if (children.length > 0) {
        children = treeLoop(children, total);
      }

      arr[i].children = children.length > 0 ? children : null;
    }

    return arr;
  }

  return treeLoop(copyArr, array);
}

export function countNewlines(text) {
  let newlineCount = 0;
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '\n') {
      newlineCount++;
    }
  }
  return newlineCount;
}

export function repictCountNewlines(text) {
  let newlineCount = 0;
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '\n') {
      newlineCount++;
    }
  }
  return newlineCount;
}

// 获取随机颜色
export function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

export function removeEmptyValues(obj) {
  const result = {};

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];
      // 检查值是否为空，这里考虑了 null、undefined、空字符串和只含空白的字符串
      if (
        value !== null &&
        value !== undefined &&
        value.toString().trim() !== ''
      ) {
        result[key] = value;
      }
    }
  }

  return result;
}
